<?php
namespace app\api\controller;

use think\Db;
use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
class Ticket
{

    private static function surfNet($query) {
       $headers = [
                'headers' => [
                    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding' => 'gzip, deflate',
                    'Accept-Language' => 'zh-CN,zh;q=0.9',
                    'Cache-Control' => 'no-cache',
                    'Host' => 'www.cbooo.cn',
                    'User-Agent' => 'Mozilla/5.0 (Linux; U; Android 4.4.3; zh-cn; HTC 802w Build/KTU84L) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025489 Mobile Safari/533.1 MicroMessenger/6.3.13.49_r4080b63.740 NetType/WIFI Language/zh_CN',
                    'Connection' => 'keep-alive',
                    'Upgrade-insecure-requests' => 1,
                    'Pragma' => 'no-cache'
                ]
       ];

        $client = new Client();

        $response= $client->request('GET',$query['url'],$headers);

        if($response->getStatusCode() == 200){
            return $response->getBody()->getContents();
        }else{
            return false;
        }
    }


    public function index(){

        $param=[];
        $param['url']='http://www.cbooo.cn/';
        $content = self::surfNet($param);
        $crawler = new Crawler($content);

        $data=[];
        $crawler->filter('.js_bg tbody tr')->each(function (Crawler $node, $i) use (&$data){
            $name =  trim($node->filter('.text_l p')->eq(0)->text());
            $ljpf =  trim($node->filter('.text_l .p3-tb')->text());
            $syts =  trim($node->filter('.text_l span')->text());
            $shpf =  trim($node->filter('.pos-r .bold')->text());
            $pfzb =  trim($node->filter('.pos-r p')->eq(1)->text());
            $ppzb =  trim($node->filter('.pos-r')->eq(1)->children('p')->text());
            $sycs =  trim($node->filter('.pos-r')->eq(2)->children('img')->text());

            $data[]=['movieName'=>$name,'allTicketMoney'=>$ljpf,'movieDay'=>$syts,
                'dayTicketMoney'=>$shpf,'ticketMoneyRate'=>$pfzb,'movieNumRate'=>$ppzb,'movieNum'=>$sycs];
        });

        $save=[];
        foreach ($data as $v){
            $savedata=[];
            $savedata['name']=$v['movieName'];
            $savedata['all_ticket']=explode('：',$v['allTicketMoney'])[1];
            $savedata['today_ticket']=$v['dayTicketMoney'];
            $savedata['pulish_date']=$v['movieDay'];
            $savedata['movie_num']=$v['movieNum'];
            $savedata['ticket_rate']=$v['ticketMoneyRate'];
            $savedata['num_rate']=$v['movieNumRate'];
            $savedata['createtime']=date('Y-m-d H:i:s');
            $save[]=$savedata;
        }

        Db::name('movie')->insertAll($save);
        echo '完成';
    }


}
